package com.springmvc.servlet;

import com.springmvc.init.handlerAdapter.HandlerAdapter;
import com.springmvc.init.handlerMapping.HandlerMapping;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

public class DispatcherServlet extends HttpServlet {

    Collection<HandlerMapping> handlerMappings;
    Collection<HandlerAdapter> handlerAdapters;

    public DispatcherServlet(){
        System.out.println("1111111111111111111111111111");
    }

    public DispatcherServlet(AnnotationConfigApplicationContext ac) {
        handlerMappings = ac.getBeansOfType(HandlerMapping.class).values();
        handlerAdapters = ac.getBeansOfType(HandlerAdapter.class).values();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Object handlerMapping = getHandlerMapping(req);
        if (handlerMapping == null) {
            throw new RuntimeException("未找到指定的mapping");
        }

        HandlerAdapter adapter = getHandlerAdapter(handlerMapping);
        if (adapter == null) {
            throw new RuntimeException("未找到指定的HandlerAdapter");
        }
        Object result = adapter.handler(req, resp, handlerMapping);

        PrintWriter writer = resp.getWriter();
        writer.println(result);
        writer.flush();
        writer.close();
    }


    private Object getHandlerMapping(HttpServletRequest request) {
        for (HandlerMapping handlerMapping : handlerMappings) {
            Object mapping = handlerMapping.gethandlerMapping(request.getRequestURI());
            if (mapping != null) {
                return mapping;
            }
        }
        return null;
    }

    private HandlerAdapter getHandlerAdapter(Object handlerMapping) {
        for (HandlerAdapter handlerAdapter : handlerAdapters) {
            boolean falg = handlerAdapter.isSuuport(handlerMapping);
            if (falg) {
                return handlerAdapter;
            }
        }
        return null;
    }
}
